package soulkun.library.helper.application

import android.app.Activity
import android.app.Application
import soulkun.library.impl.SimpleActivityLifecycleCallbacks
import soulkun.library.utils.logE

class AppFrontBackHelper {

    private var mOnAppStatusListener: OnAppStatusListener? = null
    private var activityCount = 0

    constructor(application: Application) {
        val lifecycleCallbacks = object : SimpleActivityLifecycleCallbacks() {
            override fun onActivityStarted(activity: Activity) {
                activityCount++
                if (activityCount == 1) {
                    if (mOnAppStatusListener != null) {
                        mOnAppStatusListener!!.onFront(activity)
                    }
                }
            }

            override fun onActivityStopped(activity: Activity) {
                activityCount--
                if (activityCount == 0) {
                    if (mOnAppStatusListener != null) {
                        mOnAppStatusListener!!.onBack(activity)
                    }
                }
            }
        }
        application.registerActivityLifecycleCallbacks(lifecycleCallbacks)
    }

    fun setOnAppStatusListener(listener: OnAppStatusListener?) {
        mOnAppStatusListener = listener
    }


    interface OnAppStatusListener {
        fun onFront(activity: Activity)
        fun onBack(activity: Activity)
    }

}